import React from 'react'
import { Typography, Tag, Card, Tabs, Alert, List, Badge, Statistic, Row, Col } from 'antd'
import {
  CheckCircleOutlined,
  ClockCircleOutlined,
  CodeOutlined,
  RocketOutlined,
  ThunderboltOutlined,
  BulbOutlined,
  FileTextOutlined
} from '@ant-design/icons'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import hljs from 'highlight.js/lib/core'
import javascript from 'highlight.js/lib/languages/javascript'
import typescript from 'highlight.js/lib/languages/typescript'
import bash from 'highlight.js/lib/languages/bash'
import yaml from 'highlight.js/lib/languages/yaml'
import dockerfile from 'highlight.js/lib/languages/dockerfile'
import markdown from 'highlight.js/lib/languages/markdown'
import json from 'highlight.js/lib/languages/json'
import xml from 'highlight.js/lib/languages/xml'
import css from 'highlight.js/lib/languages/css'
import { Slide } from '../types'

// 注册语言
hljs.registerLanguage('javascript', javascript)
hljs.registerLanguage('typescript', typescript)
hljs.registerLanguage('tsx', typescript)
hljs.registerLanguage('jsx', javascript)
hljs.registerLanguage('bash', bash)
hljs.registerLanguage('sh', bash)
hljs.registerLanguage('yaml', yaml)
hljs.registerLanguage('yml', yaml)
hljs.registerLanguage('dockerfile', dockerfile)
hljs.registerLanguage('markdown', markdown)
hljs.registerLanguage('json', json)
hljs.registerLanguage('xml', xml)
hljs.registerLanguage('html', xml)
hljs.registerLanguage('css', css)

const { Title, Paragraph, Text } = Typography

interface SlideContentProps {
  slide: Slide
}

const SlideContent: React.FC<SlideContentProps> = ({ slide }) => {
  const [activeTabKey, setActiveTabKey] = React.useState('0')

  // 当幻灯片改变时，重置tab选中状态
  React.useEffect(() => {
    setActiveTabKey('0')
  }, [slide])

  // 高亮代码的函数
  const highlightCode = React.useCallback(() => {
    document.querySelectorAll('.code-block pre code, pre code').forEach((block) => {
      const element = block as HTMLElement

      // 获取语言类型
      const langClass = element.className.match(/language-(\w+)/)?.[1]

      // 强制重新高亮（移除已处理标记）
      element.classList.remove('hljs-processed')

      // 保存原始内容（如果已经高亮过，需要先获取原始文本）
      let originalText = element.textContent || ''

      // 如果已经是高亮过的HTML，尝试提取原始文本
      if (element.querySelector('.hljs-keyword, .hljs-string, .hljs-number')) {
        // 已经高亮过，获取纯文本
        const tempDiv = document.createElement('div')
        tempDiv.innerHTML = element.innerHTML
        originalText = tempDiv.textContent || ''
      }

      try {
        let result
        if (langClass && hljs.getLanguage(langClass)) {
          // 指定语言高亮
          result = hljs.highlight(originalText, { language: langClass })
        } else {
          // 自动检测语言，优先检测常用语言
          const preferredLanguages = ['typescript', 'javascript', 'bash', 'yaml', 'json', 'html', 'css']
          result = hljs.highlightAuto(originalText, preferredLanguages)
          if (result.language) {
            element.classList.add(`language-${result.language}`)
          }
        }

        element.innerHTML = result.value
        element.classList.add('hljs', 'hljs-processed')

        // 确保文本颜色可见
        element.style.color = '#abb2bf'
      } catch (err) {
        console.warn(`高亮处理失败:`, err)
        // 降级处理：保持原文但加上基础样式
        element.classList.add('hljs', 'hljs-processed')
        element.style.color = '#abb2bf'
      }
    })
  }, [])

  // 监听slide和activeTabKey变化，触发高亮
  React.useEffect(() => {
    // 使用多个延迟时间，确保DOM渲染完成
    const timers = [
      setTimeout(highlightCode, 0),
      setTimeout(highlightCode, 100),
      setTimeout(highlightCode, 300)
    ]

    // 使用 MutationObserver 监听DOM变化
    const observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (mutation.type === 'childList') {
          mutation.addedNodes.forEach((node) => {
            if (node instanceof HTMLElement) {
              const codeBlocks = node.querySelectorAll?.('pre code')
              if (codeBlocks?.length > 0 || node.matches?.('pre code')) {
                setTimeout(highlightCode, 10)
              }
            }
          })
        }
      })
    })

    // 开始观察整个组件的DOM变化
    const container = document.querySelector('.slide-content-container')
    if (container) {
      observer.observe(container, {
        childList: true,
        subtree: true
      })
    }

    return () => {
      timers.forEach(timer => clearTimeout(timer))
      observer.disconnect()
    }
  }, [slide, activeTabKey, highlightCode])

  const renderContent = () => {
    switch (slide.type) {
      case 'title':
        return (
          <div className="flex flex-col items-center justify-center h-full text-center animate-fade-in">
            <Title level={1} className="text-5xl md:text-7xl mb-8 gradient-text">
              {slide.subtitle || slide.title}
            </Title>
            {slide.subtitle && (
              <Title level={2} className="text-2xl md:text-3xl text-gray-600">
                让AI成为你的编程助手
              </Title>
            )}
            {slide.description && (
              <Paragraph className="text-lg md:text-xl text-gray-500 max-w-3xl mt-8">
                {slide.description}
              </Paragraph>
            )}
            <div className="mt-12 flex flex-wrap gap-2 justify-center">
              {slide.tags?.map((tag) => (
                <Tag key={tag} color="purple" className="px-4 py-1 text-base">
                  {tag}
                </Tag>
              ))}
            </div>
          </div>
        )

      case 'overview':
        return (
          <div className="animate-slide-in overflow-hidden">
            <Title level={2} className="mb-8 gradient-text">{slide.title}</Title>
            {slide.description && (
              <Paragraph className="text-lg text-gray-600 text-center mb-8 max-w-3xl mx-auto">
                {slide.description}
              </Paragraph>
            )}
            {slide.items && (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                {slide.items.map((item, index) => (
                  <div key={index} className="w-full">
                    <Card
                      hoverable
                      className="h-full bg-gradient-to-br from-purple-50 to-pink-50 border-0"
                      bodyStyle={{ padding: '20px' }}
                    >
                      <div className="flex items-start gap-3">
                        <div className="flex-shrink-0" style={{ marginTop: '2px' }}>
                          {item.icon}
                        </div>
                        <div className="flex-1 overflow-hidden">
                          <h4 className="text-base font-semibold mb-2 text-gray-900">
                            {item.title}
                          </h4>
                          <p className="text-sm text-gray-600 m-0 leading-relaxed">
                            {item.description}
                          </p>
                        </div>
                      </div>
                    </Card>
                  </div>
                ))}
              </div>
            )}
            {slide.tags && (
              <div className="mt-8 flex flex-wrap gap-2 justify-center">
                {slide.tags.map((tag) => (
                  <Tag key={tag} color="purple" className="px-4 py-1 text-base">
                    {tag}
                  </Tag>
                ))}
              </div>
            )}
          </div>
        )

      case 'comparison':
        return (
          <div>
            <Title level={2} className="mb-8 gradient-text">{slide.title}</Title>
            <Row gutter={24}>
              <Col xs={24} md={12}>
                <Card title={
                  <span className="text-red-500">
                    <ClockCircleOutlined /> 传统开发
                  </span>
                } className="h-full">
                  <List
                    dataSource={slide.before}
                    renderItem={(item) => (
                      <List.Item>
                        <Text type="secondary">{item}</Text>
                      </List.Item>
                    )}
                  />
                </Card>
              </Col>
              <Col xs={24} md={12}>
                <Card title={
                  <span className="text-green-500">
                    <RocketOutlined /> 使用Claude
                  </span>
                } className="h-full">
                  <List
                    dataSource={slide.after}
                    renderItem={(item) => (
                      <List.Item>
                        <Text strong className="text-green-600">
                          <CheckCircleOutlined /> {item}
                        </Text>
                      </List.Item>
                    )}
                  />
                </Card>
              </Col>
            </Row>
            {slide.stats && (
              <Row gutter={24} className="mt-8">
                {slide.stats.map((stat, index) => (
                  <Col xs={12} md={6} key={index}>
                    <Card className="text-center bg-gradient-to-br from-blue-50 to-cyan-50">
                      <Statistic
                        title={stat.label}
                        value={stat.value}
                        suffix={stat.suffix}
                        prefix={stat.prefix}
                        valueStyle={{ color: stat.color }}
                      />
                    </Card>
                  </Col>
                ))}
              </Row>
            )}
          </div>
        )

      case 'code':
        return (
          <div>
            <Title level={2} className="mb-4 gradient-text">{slide.title}</Title>
            {slide.description && (
              <Alert
                message={slide.description}
                type="info"
                icon={<BulbOutlined />}
                className="mb-6"
              />
            )}
            <Tabs
              activeKey={activeTabKey}
              onChange={setActiveTabKey}
              items={slide.examples?.map((example, index) => ({
                key: String(index),
                label: (
                  <span>
                    <CodeOutlined /> {example.title}
                  </span>
                ),
                children: (
                  <div>
                    {example.description && (
                      <Paragraph className="text-gray-600 mb-4">
                        {example.description}
                      </Paragraph>
                    )}
                    {example.prompt && (
                      <Card
                        title={
                          <span className="flex items-center gap-2">
                            <FileTextOutlined className="text-purple-600" />
                            <span className="text-purple-700 font-semibold">提示词模板</span>
                          </span>
                        }
                        className="mb-4 border-2 border-purple-200 bg-gradient-to-r from-purple-50 to-blue-50"
                      >
                        <pre className="whitespace-pre-wrap text-sm font-medium" style={{
                          color: '#4a5568',
                          backgroundColor: 'rgba(255, 255, 255, 0.8)',
                          padding: '16px',
                          borderRadius: '8px',
                          border: '1px solid #e2e8f0',
                          lineHeight: '1.6'
                        }}>
                          {example.prompt}
                        </pre>
                      </Card>
                    )}
                    <div className="code-block">
                      <div className="flex justify-between items-center mb-2">
                        <div className="inline-block px-3 py-1 bg-gradient-to-r from-purple-600 to-blue-600 text-white text-sm font-medium rounded-full shadow-md">
                          {example.language || 'auto'}
                        </div>
                        <Text className="text-gray-400 text-xs">
                          可左右滑动查看
                        </Text>
                      </div>
                      <pre style={{ maxHeight: '400px', overflowY: 'auto' }}>
                        <code
                          className={example.language ? `language-${example.language}` : ''}
                          data-lang={example.language || 'auto'}
                        >
                          {example.code}
                        </code>
                      </pre>
                    </div>
                  </div>
                ),
              }))}
            />
          </div>
        )

      case 'demo':
        return (
          <div>
            <Title level={2} className="mb-8 gradient-text">{slide.title}</Title>
            {slide.description && (
              <Paragraph className="text-lg text-gray-600 mb-8">
                {slide.description}
              </Paragraph>
            )}
            {slide.steps && (
              <Card title="操作步骤" className="mb-6">
                <List
                  dataSource={slide.steps}
                  renderItem={(step, index) => (
                    <List.Item>
                      <div className="flex items-start gap-3 w-full">
                        <Badge count={index + 1} className="mt-1" />
                        <div className="flex-1">
                          <Text strong>{step.title}</Text>
                          {step.description && (
                            <Paragraph className="text-gray-600 mt-1 mb-0">
                              {step.description}
                            </Paragraph>
                          )}
                          {step.code && (
                            <div className="code-block mt-2">
                              <pre>
                                <code className="language-bash">{step.code}</code>
                              </pre>
                            </div>
                          )}
                        </div>
                      </div>
                    </List.Item>
                  )}
                />
              </Card>
            )}
            {slide.result && (
              <Alert
                message="效果展示"
                description={slide.result}
                type="success"
                icon={<ThunderboltOutlined />}
                showIcon
              />
            )}
          </div>
        )

      case 'tips':
        return (
          <div>
            <Title level={2} className="mb-8 gradient-text">{slide.title}</Title>
            <Row gutter={[16, 16]}>
              {slide.tips?.map((tip, index) => (
                <Col xs={24} md={12} key={index}>
                  <Card
                    title={
                      <span>
                        <BulbOutlined className="text-yellow-500" /> {tip.title}
                      </span>
                    }
                    className="h-full hover:shadow-lg transition-shadow"
                  >
                    <Paragraph>{tip.content}</Paragraph>
                    {tip.example && (
                      <div className="code-block mt-3">
                        <pre>
                          <code className="language-markdown">{tip.example}</code>
                        </pre>
                      </div>
                    )}
                  </Card>
                </Col>
              ))}
            </Row>
          </div>
        )

      default:
        return (
          <div>
            <Title level={2} className="mb-6 gradient-text">{slide.title}</Title>
            <div className="prose prose-lg max-w-none">
              <ReactMarkdown remarkPlugins={[remarkGfm]}>
                {slide.content || ''}
              </ReactMarkdown>
            </div>
          </div>
        )
    }
  }

  return (
    <div className="h-full overflow-auto slide-content-container">
      {renderContent()}
    </div>
  )
}

export default SlideContent